<template>
  <div class="page-container">
    <!-- 头部导航 -->
    <header class="header">
      <BackBtn />
      <h1>查询提案</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content" style="margin-top: 10px;">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-input 
          v-model="searchText" 
          placeholder="支持搜索案由、提案人、提案号" 
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button 
              type="button" 
              class="search-btn"
              @click="handleSearch"
            >
              <el-icon class="search-icon">
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>

        <div class="filter-section">
          <!-- 日期范围选择 -->
          <div class="date-range-picker">
            <el-date-picker 
              v-model="dateRange[0]" 
              type="date" 
              placeholder="开始日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
            <span class="separator">—</span>
            <el-date-picker 
              v-model="dateRange[1]" 
              type="date" 
              placeholder="结束日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
          </div>

          <!-- 时间选择 -->
          <el-select v-model="sortBy" placeholder="排序：提案时间(倒序)" @change="handleFilterChange">
            <el-option label="提案时间(倒序)" value="desc" />
            <el-option label="提案时间(正序)" value="asc" />
          </el-select>

          <!-- 类型筛选 -->
          <div class="advanced-filters">
            <el-select v-model="proposalType" @change="handleFilterChange" placeholder="提案类型：全部">
              <el-option label="类型筛选：全部" value="all" />
              <el-option label="医疗健康类" value="医疗健康类" />
              <el-option label="教育科技类" value="教育科技类" />
              <el-option label="文化体育类" value="文化体育类" />
              <el-option label="城市建设类" value="城市建设类" />
              <el-option label="环境保护类" value="环境保护类" />
              <el-option label="社会治理类" value="社会治理类" />
              <el-option label="经济发展类" value="经济发展类" />
              <el-option label="其他类" value="其他类" />
            </el-select>
          </div>

          <!-- 状态筛选 -->
          <el-select v-model="status" @change="handleFilterChange" placeholder="状态筛选：全部">
            <el-option label="状态筛选：全部" value="all" />
            <el-option label="已通过" value="复审" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>

          <!-- 导出按钮 -->
          <el-button type="danger" style="margin-left: auto" @click="handleExport">导 出</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
        <div class="news-list">
          <!-- 添加表头 -->
          <div class="news-header">
            <div class="header-item">案由</div>
            <div class="header-item" style="margin-left: 90px;">提案类型</div>
            <div class="header-item">提案人</div>
            <div class="header-item">提案时间</div>
            <div class="header-item">当前状态</div>
            <div class="header-item">公示处理</div>
          </div>
          <!-- 无数据显示 -->
          <div v-if="!tableData || tableData.length === 0" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <!-- 数据列表 -->
          <div v-else v-for="(item, index) in tableData" :key="index" class="news-item">
            <div class="line" style="margin-top: 13px;"></div>
            <div class="news-info" @click="handleRowClick(item)">
              <div class="info-value" :title="item.caseReason">{{ item.caseReason }}</div>
              <div class="info-value" :title="item.proposalType">{{ item.proposalType }}</div>
              <div class="info-value" :title="item.proposer">{{ item.proposer }}</div>
              <div class="info-value" :title="formatDate(item.isOrTime)">{{ formatDate(item.isOrTime) }}</div>
              <div class="info-value">
                <el-tag 
                  :type="getStatusType(item.status)"
                  size="small"
                >
                  {{ item.status }}
                </el-tag>
              </div>
            </div>
            <div class="news-actions">
              <el-tooltip
                effect="dark"
                :content="getPublicTooltip(item)"
                placement="top"
              >
                <el-button
                  type="primary"
                  size="small"
                  class="public-btn"
                  :class="{
                    'is-public': item.finalPublic,
                    'user-agreed': item.isPublic,
                    'user-disagreed': !item.isPublic
                  }"
                  @click="handlePublicClick(item)"
                  :disabled="!canPublish(item)"
                >
                  {{ getPublicButtonText(item) }}
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            :background="false"
            layout="prev, pager, next, jumper"
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加自定义公示弹窗 -->
    <div v-if="showPublicDialog" class="custom-dialog-overlay" @click.self="closePublicDialog">
      <div class="custom-dialog">
        <div class="dialog-content">
          <h3>公示确认</h3>
          <div class="public-info">
            <p>提案人公示意愿：
              <span :class="currentRow?.isPublic ? 'agree' : 'disagree'">
                {{ currentRow?.isPublic ? '同意公示' : '不同意公示' }}
              </span>
            </p>
            <p>管理员公示意愿：
              <span :class="currentRow?.finalPublic ? 'public' : 'private'">
                {{ currentRow?.finalPublic ? '已公示' : '未公示' }}
              </span>
            </p>
            <p class="warning" v-if="!currentRow?.isPublic">注意：提案人不同意公示，请谨慎操作</p>
          </div>
          <div class="radio-group">
            <label class="radio-label">
              <input 
                type="radio" 
                v-model="publicChoice" 
                :value="true"
                class="radio-input"
              >
              <span class="radio-text">公示</span>
            </label>
            <label class="radio-label">
              <input 
                type="radio" 
                v-model="publicChoice" 
                :value="false"
                class="radio-input"
              >
              <span class="radio-text">不公示</span>
            </label>
          </div>
          <div class="dialog-footer">
            <button class="cancel-btn" @click="closePublicDialog">取消</button>
            <button class="confirm-btn" @click="handlePublicConfirm">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { updateProposalStatus,  updatePublicStatus, exportProposals } from '@/api/proposal.js'
import { useProposalStore } from '@/stores/proposal.js'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

// 使用 proposal store
const proposalStore = useProposalStore()

// 使用 store 中的状态
const { 
  tableData,
  total,
  pageNum,
  pageSize,
  dateRange,
  sortBy,
  status,
  proposalType,
  searchText
} = storeToRefs(proposalStore)

// 筛选
const router = useRouter()
const loading = ref(false)
// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  sortBy.value = 'desc'  // 重置时间排序为默认的倒序
  proposalType.value = 'all'  // 重置提案类型为全部
  status.value = 'all'  // 重置状态筛选为全部
  pageNum.value = 1
}


// 添加公示相关的状态变量
const showPublicDialog = ref(false)
const publicChoice = ref(true)
const currentRow = ref(null)

// 在组件挂载时获取提案数据
onMounted(() => {
  resetFilters()  // 初始化重置
  loading.value = true
  proposalStore.fetchProposalData()
  loading.value = false
})

// 分页处理
const onSizeChange = (size) => {
  pageSize.value = size
  proposalStore.fetchProposalData()
}

const onCurrentChange = (num) => {
  pageNum.value = num
  proposalStore.fetchProposalData()
}

// 筛选条件变化时的处理
const handleFilterChange = () => {
  proposalStore.fetchProposalData()
}

// 处理搜索
const handleSearch = () => {
  proposalStore.fetchProposalData()
}

// 处理行点击
const handleRowClick = (row) => {
  router.push(`/proposal/detail/${row.pid}`)
}

// 获取状态对应的类型
const getStatusType = (status) => {
  const statusMap = {
    '初审': 'primary',
    '复审': 'primary',
    '分流': 'primary',
    '专项处理': 'primary',
    '最终批复': 'primary',
    '处理中':'warning',
    '已驳回': 'danger',
    '处理完结': 'success'
  }
  return statusMap[status] || 'info'
}

// 处理公示按钮点击
const handlePublicClick = (item) => {
  currentRow.value = item;
  publicChoice.value = item.finalPublic;
  showPublicDialog.value = true;
}

// 判断是否可以发布
const canPublish = (item) => {
  return ['处理完结'].includes(item.status) && item.status !== '已驳回';
}

// 获取公示按钮文本
const getPublicButtonText = (item) => {
  if (!canPublish(item)) return '待处理';
  return item.finalPublic ? '已公示' : '公示';
}

// 获取tooltip提示文本
const getPublicTooltip = (item) => {
  if (item.status === '已驳回') {
    return '提案无效，无法公示';
  }
  if (!canPublish(item)) {
    return '提案处理完结后可操作公示';
  }
  if (item.finalPublic) {
    return '点击可取消公示';
  }
  return item.isPublic ? 
    '提案人同意公示，可点击进行公示' : 
    '提案人不同意公示，请谨慎操作';
}

// 处理公示确认
const handlePublicConfirm = async () => {
  try {
    // 如果用户不同意公示，且要设置为公示，需要二次确认
    if (!currentRow.value.isPublic && publicChoice.value) {
      const confirmResult = await ElMessageBox.confirm(
        '提案人不同意公示，是否确定要公示？',
        '二次确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      if (confirmResult !== 'confirm') {
        return;
      }
    }

    await updatePublicStatus({
      pid: currentRow.value.pid,
      status: currentRow.value.status,
      isOr: publicChoice.value,
      pageStatus: 5,
      userPublicChoice: currentRow.value.isPublic
    });

    // 根据实际的选择显示不同的反馈信息
    ElMessage.success(publicChoice.value ? '提案已公示' : '提案已取消公示');
    currentRow.value.finalPublic = publicChoice.value;
    closePublicDialog();
    await proposalStore.fetchProposalData();
  } catch (error) {
    console.error('设置公示状态失败:', error);
    ElMessage.warning('设置公示状态失效');
  }
}

// 关闭弹窗
const closePublicDialog = () => {
  showPublicDialog.value = false
  publicChoice.value = true
}

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}`;
}

// 导出提案数据
const handleExport = async () => {
  try {
    loading.value = true
    
    // 格式化日期参数
    let startDate = null
    let endDate = null
    
    if (dateRange.value[0]) {
      const date = new Date(dateRange.value[0])
      startDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    if (dateRange.value[1]) {
      const date = new Date(dateRange.value[1])
      endDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 准备请求参数，与当前筛选条件保持一致
    const params = {
      pageStatus: 6, // 提案查询页面
      status: status.value !== 'all' ? status.value : null,
      proposalType: proposalType.value !== 'all' ? proposalType.value : null,
      startDate,
      endDate,
      searchText: searchText.value,
      sort: sortBy.value
    }
    
    // 调用导出API
    const response = await exportProposals(params)
    
    // 创建Blob对象
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 创建临时下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    
    // 设置文件名
    const now = new Date()
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
    link.download = `提案查询数据_${timestamp}.xlsx`
    
    // 模拟点击下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出提案数据成功')
  } catch (error) {
    console.error('导出提案数据失败:', error)
    ElMessage.error('导出提案数据失败')
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
@import '@/assets/css/proposal/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/search.css';
@import '@/assets/css/others/select.css';

.public-btn {
  min-width: 80px;
}

.public-btn.is-public {
  background-color: #67c23a;
  border-color: #67c23a;
}

.news-info {
  cursor: pointer;
}

.news-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-item {
  flex: 1;
  text-align: left;
  padding: 0 10px;
  font-weight: bold;
  color: #333;
}

/* 添加自定义弹窗样式 */
.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
}

.custom-dialog {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 300px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-content {
  text-align: center;
}

.dialog-content h3 {
  margin: 0;
  padding: 10px 0;
  font-size: 18px;
  color: #333;
}

.dialog-content p {
  margin: 10px 0;
  color: #666;
  font-size: 14px;
}

.radio-group {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  gap: 30px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-input {
  width: 18px;
  height: 18px;
  margin-right: 8px;
  accent-color: #c8102e;
}

.radio-text {
  font-size: 16px;
  color: #333;
}

.confirm-btn {
  background-color: #c8102e;
  color: white;
  border: none;
  padding: 8px 40px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-top: 10px;
}

.confirm-btn:hover {
  background-color: #a50d26;
}

.no-data {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 10px;
}

:deep(.el-empty__description) {
  margin-top: 10px;
  color: #909399;
}

.public-btn.user-agreed {
  border-color: #67c23a;
}

.public-btn.user-disagreed {
  border-color: #f56c6c;
}

.public-info {
  margin: 15px 0;
  text-align: left;
  padding: 0 20px;
}

.public-info .agree {
  color: #67c23a;
  font-weight: bold;
}

.public-info .disagree {
  color: #f56c6c;
  font-weight: bold;
}

.public-info .warning {
  color: #e6a23c;
  font-size: 12px;
  margin-top: 5px;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.cancel-btn {
  background-color: #909399;
  color: white;
  border: none;
  padding: 8px 20px;
  height: 40px;
  margin-top: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #82848a;
}

.confirm-btn {
  background-color: #c8102e;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn:hover {
  background-color: #a50d26;
}

.public-info .public {
  color: #67c23a;
  font-weight: bold;
}

.public-info .private {
  color: #909399;
  font-weight: bold;
}

.public-btn:not(.is-public) {
  background-color: #409eff;
  border-color: #409eff;
}

.public-btn:disabled {
  background-color: #a0cfff;
  border-color: #a0cfff;
  cursor: not-allowed;
}
</style>

<style>
/* 调整 Element Plus MessageBox 的层级 */
.el-message-box__wrapper {
  z-index: 999999 !important;
}

.el-overlay {
  z-index: 999998 !important;
}

.el-message {
  z-index: 999999 !important;
}
</style>